// resolver文件（写接口）
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import { FindOptionsWhere, Like } from 'typeorm';
import { OrganizationService } from './Organization.service';
import { UseGuards } from '@nestjs/common';
import { GqlAuthGuard } from '@/common/guards/auth.guard';
import { CurUserId } from '@/common/decorators/current-user.decorator';
import {
  OrganizationResult,
  OrganizationResults,
} from './dto/result-Organization.output';
import { OrganizationType } from './dto/Organization.type';
import {
  ORG_DEL_FAIL,
  ORG_FAIL,
  ORG_NOT_EXIST,
  SUCCESS,
} from '@/common/constants/code';
import { OrganizationInput } from './dto/Organization-input.type';
import { Result } from '@/common/dto/result.type';
import { PageInput } from '@/common/dto/page.input';
import { OrgImageService } from '../orgImage/orgImage.service';
import { Organization } from './models/organization.entity';

@Resolver(() => OrganizationType)
@UseGuards(GqlAuthGuard)
export class OrganizationResolver {
  constructor(
    private readonly organizationService: OrganizationService,
    private readonly orgImageService: OrgImageService,
  ) {}
  // 详情
  @Query(() => OrganizationResult)
  async getOrganizationInfo(
    @Args('id') id: string,
  ): Promise<OrganizationResult> {
    const result = await this.organizationService.findById(id);
    if (result) {
      return {
        code: SUCCESS,
        data: result,
        message: '获取成功',
      };
    }
    return {
      code: ORG_NOT_EXIST,
      message: '门店信息不存在',
    };
  }

  // 修改
  @Mutation(() => OrganizationResult)
  async commitOrganization(
    @Args('params') params: OrganizationInput,
    @CurUserId() userId: string,
    @Args('id', { nullable: true }) id?: string,
  ): Promise<Result> {
    if (id) {
      // 编辑
      const organization = await this.organizationService.findById(id);
      if (!organization) {
        return {
          code: ORG_NOT_EXIST,
          message: '门店信息不存在',
        };
      }
      const delRes = await this.orgImageService.deleteByOrg(id);
      if (!delRes) {
        return {
          code: ORG_FAIL,
          message: '图片删除不成功，无法更新门店信息',
        };
      }
      const res = await this.organizationService.updateById(id, {
        ...params,
        updatedBy: userId,
      });
      if (res) {
        return {
          code: SUCCESS,
          message: '更新成功',
        };
      }
    } else {
      // 新增
      const res = await this.organizationService.create({
        ...params,
        createdBy: userId,
      });
      if (res) {
        return {
          code: SUCCESS,
          message: '创建成功',
        };
      }
      return {
        code: ORG_FAIL,
        message: '操作失败',
      };
    }
  }

  // 查询
  @Query(() => OrganizationResults)
  async getOrganizations(
    @Args('page') page: PageInput,
    @CurUserId() userId: string,
    @Args('name', { nullable: true }) name?: string,
  ): Promise<OrganizationResults> {
    const { pageNum, pageSize } = page;
    const where: FindOptionsWhere<Organization> = { createdBy: userId };
    if (name) {
      where.name = Like(`%${name}%`); // %号的意思是前后都可以有东西，模糊的查询
    }
    const [results, total] = await this.organizationService.findOrganizations({
      start: (pageNum - 1) * pageSize,
      length: pageSize,
      where,
    });
    if (results) {
      return {
        code: SUCCESS,
        data: results,
        page: {
          pageNum,
          pageSize,
          total,
        },
        message: '获取成功',
      };
    }
  }

  // 删除
  @Mutation(() => Result)
  async deleteOrganization(
    @Args('id') id: string,
    @CurUserId() userId: string,
  ) {
    const result = await this.organizationService.findById(id);
    if (result) {
      const res = await this.organizationService.deleteById(id, userId);
      if (res) {
        return {
          code: SUCCESS,
          message: '删除成功',
        };
      } else {
        return {
          code: ORG_DEL_FAIL,
          message: '门店删除失败',
        };
      }
    } else {
      return {
        code: ORG_NOT_EXIST,
        message: '门店信息不存在',
      };
    }
  }
}
